package com.android.manghe.market.activity

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.ToastUtil
import com.android.manghe.R
import com.android.manghe.config.events.RefreshCartEvent
import com.android.manghe.market.adapter.CartPageAdapter
import com.android.manghe.market.adapter.multi.CartGoodLevel
import com.android.manghe.market.adapter.multi.CartRecommendLevel
import com.android.manghe.market.model.CartGoodListRes
import com.android.manghe.market.presenter.PCart
import com.android.manghe.orderpay.activity.MarketOrderPayFromCartActivity
import com.android.manghe.orderpay.activity.NoPriceMarketOrderPayFromCartActivity
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import kotlinx.android.synthetic.main.activity_cart.*
import java.text.DecimalFormat

class CartActivity : MVPActivity<PCart>() {

    private var adapter: CartPageAdapter? = null
    private var isEdit = false

    override fun getLayoutId(): Int {
        return R.layout.activity_cart
    }

    override fun initData(savedInstanceState: Bundle?) {
        titleBar.setToolbar("购物车").setLeftIcon(R.mipmap.icon_back_black)
            .setTitleAndStatusBgColor(R.color.white)
            .setRightText("编辑") {
                if(!p.goodList.isNullOrEmpty()) {
                    isEdit = !isEdit
                    adapter?.setEditMode(isEdit)
                    layoutBottomBar.visibility = if (isEdit) View.GONE else View.VISIBLE
                    titleBar.setRightText(if (isEdit) "完成" else "编辑")
                }
            }

        Bus.observe<RefreshCartEvent>().subscribe {
            p.loadCardGoodData(false)
        }.registerInBus(this)
        val itemEntityList = java.util.ArrayList<MultiItemEntity>()
        itemEntityList.add(CartGoodLevel(p.goodList))
        itemEntityList.add(CartRecommendLevel(arrayListOf()))
        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = CartPageAdapter(this, itemEntityList)
        recyclerView.adapter = adapter
        adapter!!.setListener(object : CartPageAdapter.IModifyCallBack{
            override fun onModified(
                selectedGoodList: MutableList<CartGoodListRes.DataBean.CartGoodsBean>?,
                totalPrice: Double
            ) {
                val format = DecimalFormat("0.00")
                tvTotalPrice.text = "￥${format.format(totalPrice)}"
            }

            override fun modifyGoodNum(goodId: String?, num: Int, spec: String?, isSelected: Boolean) {
                p.modifyCardGood(goodId, spec, num, isSelected)
            }

            override fun onDelete(id: String?) {
                p.deleteCartGood(id)
            }

        })

        tvOriginalBuy.setOnClickListener {
            if(p.goodList.isEmpty()){
                ToastUtil.showLong(this@CartActivity, "购物车中无商品可结算哦")
                return@setOnClickListener
            }
            adapter?.let {
                val selectedGoodList = it.selectedCartGoodList
                if(selectedGoodList.size == 0){
                    ToastUtil.showLong(this@CartActivity, "请勾选您要结算的商品")
                    return@setOnClickListener
                }
                open(MarketOrderPayFromCartActivity::class.java, hashMapOf<String, Any>(
                    "selectedGoodList" to selectedGoodList,
                    "flowUserScore" to p.flowUserScore,
                    "isMember" to p.isMember
                ))
            }

        }
        ivCheckAll.setOnClickListener {
            //全选
            if (!p.goodList.isNullOrEmpty()) {
                adapter?.let {
                    val isSelected = it.toggleSelectedAll()
                    ivCheckAll.setImageResource(if (isSelected) R.mipmap.tick_click else R.mipmap.icon_tick_default)
                }
            }
        }
        layoutMainDan.setOnClickListener {
            if(p.goodList.isEmpty()){
                ToastUtil.showLong(this@CartActivity, "购物车中无商品可结算哦")
                return@setOnClickListener
            }
            adapter?.let {
                val selectedGoodList = it.selectedCartGoodList
                if(selectedGoodList.size == 0){
                    ToastUtil.showLong(this@CartActivity, "请勾选您要结算的商品")
                    return@setOnClickListener
                }
                open(NoPriceMarketOrderPayFromCartActivity::class.java, hashMapOf<String, Any>(
                    "selectedGoodList" to selectedGoodList
                ))
            }
        }

        p.loadCardGoodData(true)
        p.loadRecommendGoods()
        p.getMemberInfo()
    }

    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }

    fun updateCartGoods() {
        adapter?.let {
            it.setData(0, CartGoodLevel(p.goodList))
        }
    }

    fun updateRecommendGoods() {
        adapter?.let {
            it.setData(1, CartRecommendLevel(p.recommendGoodList))
        }
    }
}